<?php

/**
 * alltosun.com 公用函数库 common.php
 * ============================================================================
 * 版权所有 (C) 2009-2011 北京互动阳光科技有限公司，并保留所有权利。
 * 网站地址: http://www.alltosun.com
 * ----------------------------------------------------------------------------
 * 许可声明：这是一个开源程序，未经许可不得将本软件的整体或任何部分用于商业用途及再发布。
 * ============================================================================
 * $Author: 高竞竞 (gaojj@alltosun.com) $
 * $Date: 2010-12-28 下午03:21:58 $
 * $Id: common.php 10243 2012-05-30 11:09:28Z qianym $
 */


/**
 * 写入log日志
 * @param unknown_type $data
 */
function write_log($data) {
    error_log(json_encode($data));
}

/**
 * 封装分页操作，app获取字段常用,自动分配分页
 * @param string $table_name 表名
 * @param string $fields 字段名
 * @param array $filter 条件数组
 * @param string $order 排序
 * @param int $page_no 页码
 * @param int $per_page 每页数量
 * @return array
 */
function get_app_fields($table_name, $fields, $filter = array(1 => 1), $order = ' ORDER BY `id` DESC ', $page_no = 1, $per_page = 30) {
    $page_arr = $data = array();
    $count = _model($table_name)->getTotal($filter, $order);
    if ($count) {
        $pager = new Pager($per_page);

        $pager->generate($count);
        $page_arr['page_no'] = $page_no;
        $page_arr['pages'] = $pager->getPages();


        $list = _model($table_name)->getFields($fields, $filter, ' ' . $order . ' ' . $pager->getLimit($page_no));
        $data['page'] = $page_arr;
        $data['fields'] = $list;

        return $data;
    }

    return false;
}

/**
 * 封装分页操作，app获取数据常用,自动分配分页
 * @param string $table_name 表名
 * @param array $filter 条件数组
 * @param string $order 排序
 * @param int $page_no 页码
 * @param int $per_page 每页数量
 * @return array
 */
function get_app_data_list($table_name, $filter = array(1 => 1), $order = ' ORDER BY `id` DESC ', $page_no = 1, $per_page = 30) {
    $page_arr = $data = array();
    $count = _model($table_name)->getTotal($filter, $order);

    if ($count) {
        $pager = new Pager($per_page);

        $pager->generate($count);
        $page_arr['page_no'] = $page_no;
        $page_arr['pages'] = $pager->getPages();


        $list = _model($table_name)->getList($filter, ' ' . $order . ' ' . $pager->getLimit($page_no));
        $data['page'] = $page_arr;
        $data['data'] = $list;

        return $data;
    }

    return false;
}


/**
 * 封装分页操作，后台获取数据常用,自动分配分页
 * @param string $table_name 表名
 * @param array $filter 条件数组
 * @param string $order 排序
 * @param int $page_no 页码
 * @param int $per_page 每页数量
 * @return array
 */
function get_data_list($table_name, $filter = array(1 => 1), $order = ' ORDER BY `id` DESC ', $page_no = 1, $per_page = 30) {
    $count = _model($table_name)->getTotal($filter, $order);

    if ($count) {
        $pager = new Pager($per_page);
        if ($pager->generate($count)) {
            Response::assign('pager', $pager);
        }

        Response::assign('count', $count);
        $list = _model($table_name)->getList($filter, ' ' . $order . ' ' . $pager->getLimit($page_no));
        return $list;
    }

    return array();
}

function get_data_list_all($table_name, $filter = array(1 => 1), $order = ' ORDER BY `id` DESC ') {
    //$count = _model($table_name)->getTotal($filter, $order);

    $list = _model($table_name)->getList($filter, $order);
    if (!empty($list)) {
        return $list;
    }
    return array();
}

/**
 * 检查二进制文件是否符合大小
 * @param unknown_type $image_name
 * @param unknown_type $data
 * @return string|boolean
 */
function check_size($image_name, $data) {
    set_time_limit(0);
    $file_max_size = Config::get('attachment_max_size');

    $file_name = time() . mt_rand(1, 10000) . substr($image_name, -4);
    $file_path = '/tmp/' . $file_name;

    if (file_put_contents($file_path, $data) !== false) {
        $size = sprintf("%u", filesize($file_path));
        return array('tmp_file' => $file_name, 'result' => $file_max_size > $size);
    }

    return array('result' => false);
}


/**
 * 移动图片到指定目录
 * @param unknown_type $image_name
 * @param unknown_type $data
 * @return string|boolean
 */
function move_image($file) {
    if (!ONDEV) {

        $file_dir = '/tmp/';
        $file_path = $file_dir . $file;

        if (!file_exists(UPLOAD_PATH . $file_dir)) {
            // 修改目录权限 777
            $old_umask = umask(0);
            mkdir(UPLOAD_PATH . $file_dir, 0777, true);
            umask($old_umask);
        }

        if (rename('/tmp/' . $file, UPLOAD_PATH . $file_path)) {
            umask($old_umask);
            return $file_path;
        }

        umask($old_umask);

    } else {

        $old_umask = 0;
        set_time_limit(0);

        $file_dir = date('/Y/m/d/');
        $file_path = $file_dir . $file;

        if (!file_exists(UPLOAD_PATH . $file_dir)) {
            // 修改目录权限 777
            $old_umask = umask(0);
            mkdir(UPLOAD_PATH . $file_dir, 0777, true);
            umask($old_umask);
        }

        if (rename('/tmp/' . $file, UPLOAD_PATH . $file_path)) {
            umask($old_umask);
            return $file_path;
        }

        umask($old_umask);
    }

    return false;
}

/**
 * 根据用户cookie状态和设备显示不同的模板
 */
function display_template($tpl) {
    // 判断手机端是否存在此模板
    if (in_mobile()) {
        $tmp_tpl = 'm/' . $tpl;
        $tpl_dirs = Response::getView()->getTemplateDir();
        foreach ($tpl_dirs as $path) {
            if (file_exists($path . '/' . $tmp_tpl)) {
                Response::display($tmp_tpl);
                return $tmp_tpl;
            }
        }
    }

    Response::display($tpl);
    return $tpl;
}

/**
 * 判断是否在手机上
 */
function in_mobile() {
    $device_type = Cookie::get('device_type');

    if (!$device_type) {
        if (is_mobile()) {
            $device_type = 'mobile';
        } else {
            $device_type = 'pc';
        }
    }

    switch ($device_type) {
        case 'pc':
            $is_in_mobile = false;
            break;
        case 'mobile':
            $is_in_mobile = true;
            break;
    }
    return $is_in_mobile;
}

/**
 * 判断浏览器是否为ie678
 */
function is_ie678() {
    if (false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.0') ||
        false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 7.0') ||
        false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 8.0')
    ) {
        return true;
    }
    return false;
}

/**
 * 价格转换
 * @param number $price
 * @param number $float
 * @return boolean|string
 */
function number_price($price, $float = 0) {
    if (!price) {
        return false;
    }

    return number_format((int)$price, (int)$float);
}

/**
 * 保留两位小数，四舍五入
 * @param  [type] $num [description]
 * @return [type]      [description]
 */
function num_keep_two_round($num) {
    return sprintf("%.2f", $num);
}

/**
 * 保留两位小数，不四舍五入
 * @param  [type] $num [description]
 * @return [type]      [description]
 */
function num_keep_two_not_round($num) {
    return floor($num * 100) / 100;
}


/**
 * 配合JS中YiYun.Window.Open()方法打开的弹出窗口数据回调
 * @param array $data 传递给回调方法的数据，函数会进行json_encode处理
 * @param bool $close_window 传递数据完毕后是否关闭弹出窗口，默认为不关闭
 * @return string
 * @author gaojj@alltosun.com
 */
function send_data_to_window_opener($close_window = false) {
    $close_window_code = $close_window ? 'window.close();' : '';
    $redirect_url = SITE_URL;
    return <<<CODE
    <script type="text/javascript">
        var host = null;
        if (window.opener) {
            try {
                // test if we have access to the document
                if (window.opener.document.title) {
                    host = window.opener;
                }
            }catch (e) {}
            if (host) {
                host.location.reload();
                {$close_window_code}
            } else {
                window.location.href = "{$redirect_url}";
            }
        } else {
            window.location.href = "{$redirect_url}";
        }
    </script>
CODE;
}


/**
 * curl 函数
 * @param string $url 请求的地址
 * @param string $type POST/GET/post/get
 * @param array $data 要传输的数据
 * @param string $err_msg 可选的错误信息（引用传递）
 * @param int $timeout 超时时间
 * @param array 证书信息
 * @param array $param 其他配置参数
 * @author liw@alltosun.com
 */
function curl_request($url, $type, $data = false, &$err_msg = null, $timeout = 20, $cert_info = array(), $param = array()) {
    $type = strtoupper($type);
    if ($type == 'GET' && is_array($data)) {
        $data = http_build_query($data);
    }

    $option = array();

    if ($type == 'POST') {
        $option[CURLOPT_POST] = 1;
    }
    if ($data) {
        if ($type == 'POST') {
            $option[CURLOPT_POSTFIELDS] = $data;
        } elseif ($type == 'GET') {
            $url = strpos($url, '?') !== false ? $url . '&' . $data : $url . '?' . $data;
        }
    }

    $option[CURLOPT_URL] = $url;
    $option[CURLOPT_FOLLOWLOCATION] = TRUE;
    $option[CURLOPT_MAXREDIRS] = 4;
    $option[CURLOPT_RETURNTRANSFER] = TRUE;
    $option[CURLOPT_TIMEOUT] = $timeout;

    //设置证书信息
    if (!empty($cert_info) && !empty($cert_info['cert_file'])) {
        $option[CURLOPT_SSLCERT] = $cert_info['cert_file'];
        $option[CURLOPT_SSLCERTPASSWD] = $cert_info['cert_pass'];
        $option[CURLOPT_SSLCERTTYPE] = $cert_info['cert_type'];
    }

    //设置CA
    if (!empty($cert_info['ca_file'])) {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 1;
        $option[CURLOPT_SSL_VERIFYHOST] = false;
        $option[CURLOPT_CAINFO] = $cert_info['ca_file'];

        // 设置证书目录 2015-04-14 add
        if (!empty($cert_info['ca_path'])) {
            $option[CURLOPT_CAPATH] = $cert_info['ca_path'];
        }
    } else {
        // 对认证证书来源的检查，0表示阻止对证书的合法性的检查。1需要设置CURLOPT_CAINFO
        $option[CURLOPT_SSL_VERIFYPEER] = 0;
        $option[CURLOPT_SSL_VERIFYHOST] = false;
    }
    
    if ($param) {
        //header信息
        if (isset($param['header']) && $param['header']) {
            $option[CURLOPT_HTTPHEADER] = $param['header'];
        }
    }

    $ch = curl_init();
    curl_setopt_array($ch, $option);
    $response = curl_exec($ch);
    $curl_no = curl_errno($ch);
    $curl_err = curl_error($ch);

    curl_close($ch);

    // error_log
    if ($curl_no > 0) {
        if ($err_msg !== null) {
            $err_msg = '(' . $curl_no . ')' . $curl_err;
        }
    }
    return $response;
}

/**
 * 是否手机端
 */
function is_mobile() {
    $user_agent = $_SERVER['HTTP_USER_AGENT'];
    $mobile_agents = array(
        "240x320",
        "acer",
        "acoon",
        "acs-",
        "abacho",
        "ahong",
        "airness",
        "alcatel",
        "amoi",
        "android",
        "anywhereyougo.com",
        "applewebkit/525",
        "applewebkit/532",
        "asus",
        "audio",
        "au-mic",
        "avantogo",
        "becker",
        "benq",
        "bilbo",
        "bird",
        "blackberry",
        "blazer",
        "bleu",
        "cdm-",
        "compal",
        "coolpad",
        "danger",
        "dbtel",
        "dopod",
        "elaine",
        "eric",
        "etouch",
        "fly ",
        "fly_",
        "fly-",
        "go.web",
        "goodaccess",
        "gradiente",
        "grundig",
        "haier",
        "hedy",
        "hitachi",
        "htc",
        "huawei",
        "hutchison",
        "inno",
        "ipad",
        "ipaq",
        "ipod",
        "jbrowser",
        "kddi",
        "kgt",
        "kwc",
        "lenovo",
        "lg ",
        "lg2",
        "lg3",
        "lg4",
        "lg5",
        "lg7",
        "lg8",
        "lg9",
        "lg-",
        "lge-",
        "lge9",
        "longcos",
        "maemo",
        "mercator",
        "meridian",
        "micromax",
        "midp",
        "mini",
        "mitsu",
        "mmm",
        "mmp",
        "mobi",
        "mot-",
        "moto",
        "nec-",
        "netfront",
        "newgen",
        "nexian",
        "nf-browser",
        "nintendo",
        "nitro",
        "nokia",
        "nook",
        "novarra",
        "obigo",
        "palm",
        "panasonic",
        "pantech",
        "philips",
        "phone",
        "pg-",
        "playstation",
        "pocket",
        "pt-",
        "qc-",
        "qtek",
        "rover",
        "sagem",
        "sama",
        "samu",
        "sanyo",
        "samsung",
        "sch-",
        "scooter",
        "sec-",
        "sendo",
        "sgh-",
        "sharp",
        "siemens",
        "sie-",
        "softbank",
        "sony",
        "spice",
        "sprint",
        "spv",
        "symbian",
        "tablet",
        "talkabout",
        "tcl-",
        "teleca",
        "telit",
        "tianyu",
        "tim-",
        "toshiba",
        "tsm",
        "up.browser",
        "utec",
        "utstar",
        "verykool",
        "virgin",
        "vk-",
        "voda",
        "voxtel",
        "vx",
        "wap",
        "wellco",
        "wig browser",
        "wii",
        "windows ce",
        "wireless",
        "xda",
        "xde",
        "zte"
    );
    $is_mobile = false;
    foreach ($mobile_agents as $device) {
        if (stristr($user_agent, $device)) {
            $is_mobile = true;
            break;
        }
    }
    return $is_mobile;
}


/**
 * 配合file_uploader组件处理附件与资源的关联数据
 * @param int $res_id 资源id
 * @param int $res_type 资源类型
 * @return
 * @author gaojj@alltosun.com
 */
function file_uploader_handler($res_id, $res_name) {
    if (is_numeric($res_name)) {
        $res_name = get_resource($res_name, 'name');
    }

    // 新增的附件array(0=>191, 1=>192, 2=>199, 3=>附件id);
    $attachment_ids = Request::Post('attachments', array());
    // 更新的附件array(291, 292, 293, 附件id（专辑此处是图片的id）);
    $default_attachment_ids = Request::Post('default_attachments', array());
    //    if (empty($attachment_ids)) return false;

    // 附件描述
    $description = Request::Post('description', array());
    $default_description = Request::Post('default_description', array());
    // 排序
    $view_order = Request::Post('view_order', array());
    $default_view_order = Request::Post('default_view_order', array());
    $view_keys = Request::Post('view_keys', array());

    // 资源封面（文件路径）
    $cover = Request::Post('cover', '');
    // 获取资源信息
    $res_info = _uri($res_name, $res_id);
    if (!empty($cover) && $res_info['cover'] != $cover) {
        // 更新资源封面
        _model($res_name)->update(array('id' => $res_id), array('cover' => $cover));
    }

    // 编辑
    // 获取资源的附件
    $res_attachments = get_res_attachments($res_name, $res_id);
    $res_attachment_ids = $deleted_attachments = array();
    if (!empty($res_attachments)) {
        foreach ($res_attachments as $v) {
            // get_res_attachments返回的'id'=>'defaultAttach_1'
            $res_attachment_ids[] = $v['id'];
        }
        // 删除的附件
        $deleted_attachments = array_diff($res_attachment_ids, $default_attachment_ids);
    }

    // 更新的附件
    $default_attachment_ids = array_intersect($default_attachment_ids, $res_attachment_ids);

    // 如果是专辑album，则先产生图片模型image，再关联附件attachment
    // 用uploader_desc_mark($res_type)方法来标识上传的附件是否有标题和描述
    if (uploader_desc_mark($res_name)) {
        $image_res_name = 'image';

        // 删除的附件（此处是图片的id）
        if (!empty($deleted_attachments)) {
            foreach ($deleted_attachments as $v) {
                // 关联的专辑和图片
                $delete_relation = array(
                    'relation_id' => $res_id,
                    'relation_name' => $res_name,
                    'res_id' => $v,
                    'res_name' => $image_res_name
                );
                _model('res_relation')->delete($delete_relation);
                _model('attachment_relation')->delete(array('res_name' => $image_res_name, 'res_id' => $v));
            }
        }

        // 新增的附件（此处是附件的id）
        if (!empty($attachment_ids)) {
            $attachment_titles = Request::Post('attachment_titles', array());
            $attachment_intros = Request::Post('attachment_intros', array());

            foreach ($attachment_ids as $k => $v) {
                // @FIXME 如果关联到产品资源的话，需要注意产品资源的名称是name，此处暂没考虑
                $image_title = !empty($attachment_titles[$k]) ? $attachment_titles[$k] : $res_info['title'];
                $image_intro = !empty($attachment_intros[$k]) ? $attachment_intros[$k] : $res_info['intro'];
                // 排序
                $image_order = !empty($view_order[$k]) ? $view_order[$k] : 0;
                $image_cover = _uri('attachment', $v, 'path');

                $image_info = array(
                    'res_name' => $image_res_name,
                    'user_id' => user_helper::get_user_id(),
                    'title' => $image_title,
                    'cover' => $image_cover,
                    'category_id' => $res_info['category_id'],
                    'intro' => $image_intro
                );
                $image_id = _model('image')->create($image_info);

                if ($image_id) {
                    // 关联专辑和图片
                    $relation_info = array(
                        'relation_id' => $res_id,
                        'relation_name' => $res_name,
                        'res_id' => $image_id,
                        'res_name' => $image_res_name,
                        'view_order' => $image_order
                    );
                    _model('res_relation')->create($relation_info, 'REPLACE');

                    // 关联图片和附件
                    // add_relation中采用REPLACE INTO
                    /*
                    $relation_info = array(
                        'res_id'        => $image_id,
                        'res_type'      => $image_res_type,
                        'attachment_id' => $v
                    );
                    _model('attachment_relation')->create($relation_info);
                    */
                    _model('attachment_relation')->add_relation($image_id, $image_res_name, $v);
                }
            }
        }

        // 更新的附件（此处是图片的id）
        // @FIXME 采用Ajax更新可以不需要集体更新
        if (!empty($default_attachment_ids)) {
            $default_attachment_titles = Request::Post('default_attachment_titles', array());
            $default_attachment_intros = Request::Post('default_attachment_intros', array());

            foreach ($default_attachment_ids as $v) {
                // $v是image_id
                // @FIXME 如果关联到产品资源的话，需要注意产品资源的名称是name，此处暂没考虑
                $image_title = isset($default_attachment_titles[$v]) && !empty($default_attachment_titles[$v])
                    ? $default_attachment_titles[$v] : $res_info['title'];
                $image_intro = isset($default_attachment_intros[$v]) && !empty($default_attachment_intros[$v])
                    ? $default_attachment_intros[$v] : $res_info['intro'];
                // 排序
                $image_order = isset($default_view_order[$v]) && !empty($default_view_order[$v])
                    ? $default_view_order[$v] : 0;

                $image_info = array(
                    'title' => $image_title,
                    'category_id' => $res_info['category_id'],
                    'intro' => $image_intro
                );

                _model('image')->update($v, $image_info);

                // 更新排序
                // 关联专辑和图片
                $relation_info = array(
                    'relation_id' => $res_id,
                    'relation_name' => $res_name,
                    'res_id' => $v,
                    'res_name' => $image_res_name,
                    'view_order' => $image_order
                );
                _model('res_relation')->create($relation_info, 'REPLACE');
            }
        }
    } else {
        // 普通模型关联的附件
        // 删除掉的附件（此处是附件的id）
        if (!empty($deleted_attachments)) {
            $attchment_res_name = 'attachment';
            foreach ($deleted_attachments as $v) {
                _model('attachment_relation')->delete(array(
                    'attachment_id' => $v,
                    'res_name' => $res_name,
                    'res_id' => $res_id
                ));
            }
        }

        if (!empty($attachment_ids)) {

            // 新增的附件
            foreach ($attachment_ids as $k => $v) {
                if (!empty($default_attachment_ids)) {
                    // 排序
                    $attachment_order = isset($view_keys[$k]) && !empty($view_keys[$k]) ? $view_keys[$k] : 0;
                } else {
                    // 排序
                    $attachment_order = isset($view_order[$k]) && !empty($view_order[$k]) ? $view_order[$k] : 0;
                }

                // 说明
                $attachment_description = isset($description[$k]) && !empty($description[$k]) ? $description[$k] : '';
                _model('attachment')->update($v, array('description' => $attachment_description));

                // add_relation中采用REPLACE INTO
                $relation_info = array(
                    'res_id' => $res_id,
                    'res_name' => $res_name,
                    'attachment_id' => $v,
                    'view_order' => $attachment_order
                );
                _model('attachment_relation')->create($relation_info, 'REPLACE');
            }
        }
        if (!empty($default_attachment_ids)) {
            // 更新的附件
            foreach ($default_attachment_ids as $v) {
                // 排序
                $attachment_order = isset($default_view_order[$v]) && !empty($default_view_order[$v])
                    ? $default_view_order[$v] : 0;
                // 附件描述
                $attachment_description = isset($default_description[$v]) && !empty($default_description[$v])
                    ? $default_description[$v] : '';
                _model('attachment')->update($v, array('description' => $attachment_description));

                // 更新排序
                $relation_info = array(
                    'res_id' => $res_id,
                    'res_name' => $res_name,
                    'attachment_id' => $v,
                );
                // 更新排序
                $relation_arr = array(
                    'view_order' => $attachment_order
                );
                _model('attachment_relation')->update($relation_info, $relation_arr);
            }
        }
    }
    return true;
}

/**
 * 该方法用来标识上传的附件是否有标题和描述
 * @param $res_type 资源类型
 * @return int 注：smarty里接受不到false，改为int
 * @author gaojj@alltosun.com
 */
function uploader_desc_mark($res_name) {
    // 目前只有album和env有标题和描述
    $mark = 0;
    // @FIXME 修改为从album衍生的模型都有mark
    if ('env' == $res_name || 'album' == $res_name || 'article' == $res_name) {
        $mark = 1;
    }
    return $mark;
}

/**
 * 获取资源的附件
 * @param $res_type 资源类型
 * @param $res_id 资源号
 * @return array(array('id'=>'defaultAttach_1', 'name'=>'', 'size'=>1, 'title'=>'', 'intro'=>'', 'path'=>''));
 * @author gaojj@alltosun.com
 */
function get_res_attachments($res_name, $res_id) {
    if (empty($res_id)) {
        return array();
    }

    $res_attachments = array();

    $attchment_res_name = 'attachment';

    // 获取资源信息
    $res_info = _uri($res_name, $res_id);

    if (empty($res_info['cover'])) {
        $res_info['cover'] = '';
    }

    // 如果是专辑album，则先获取图片模型image，再关联附件attachment
    // 用uploader_desc_mark($res_type)方法来标识上传的附件是否有标题和描述
    if (uploader_desc_mark($res_name)) {

        // 获取专辑的图片
        $image_res_name = 'image';
        $res_relation = array(
            'relation_id' => $res_id,
            'relation_name' => $res_name,
            'res_name' => $image_res_name
        );
        $image_list = _model('res_relation')->getList($res_relation, 'ORDER BY `view_order` ASC');

        //获取图片对应的附件
        $image_attachments = array();
        foreach ($image_list as $v) {
            $attachment_relation = array(
                'res_id' => $v['res_id'],
                'res_name' => $image_res_name
            );

            $image_info = _uri($image_res_name, $v['res_id']);

            $image_attachment = _model('attachment_relation')->read($attachment_relation);

            $attachment_info = _uri($attchment_res_name, $image_attachment['attachment_id']);

            $path_info = pathinfo($attachment_info['path']);

            $image_attachments = array(
                'id' => $image_info['id'], //此处是图片的id
                'name' => $attachment_info['file_name'],
                'size' => $attachment_info['size'],
                'title' => $image_info['title'],
                'intro' => $image_info['intro'],
                'path' => $attachment_info['path'],
                'cover' => $res_info['cover'],
                'extension' => $path_info['extension'],
                'description' => $attachment_info['description']
            );

            $res_attachments[] = $image_attachments;
        }
    } else {
        //获取资源的附件
        $attachment_relation = array(
            'res_id' => $res_id,
            'res_name' => $res_name
        );

        $attachment_list = _model('attachment_relation')->getList($attachment_relation, 'ORDER BY `view_order` ASC');

        foreach ($attachment_list as $v) {
            $attachment_info = _uri($attchment_res_name, $v['attachment_id']);
            $path_info = pathinfo($attachment_info['path']);

            $res_attachments[] = array(
                'id' => $attachment_info['id'], //此处是附件的id
                'name' => $attachment_info['file_name'],
                'size' => $attachment_info['size'],
                'path' => $attachment_info['path'],
                'type' => $attachment_info['type'],
                'cover' => $res_info['cover'],
                'extension' => $path_info['extension'],
                'description' => $attachment_info['description']
            );
        }
    }

    return $res_attachments;
}

/**
 * 获取指定路径图片的缩略图
 * @param string $path 图片路径
 * @param string $prefix 缩略图前缀名称：''-原始图片（默认）；small-小图； middle-中图；big-大图……
 * @param string @res_name 图片所属资源（用来显示指定资源的默认图）
 * @return string 图片的完整路径
 * @author gaojj@alltosun.com
 */
function _image($path, $prefix = '', $res_name = '') {
    if (!ONDEV) {
        if (stripos($path, 'http') === 0) {
            return $path;
        }
        return aliysso_helper::_image($path, $prefix);
    } else {

        // @FIXME general.gif默认图片，如果视频、文章等默认图片不同的话则存在问题
        if (!$path) {
            if (!$res_name) {
                return STATIC_URL . '/images/default/' . $prefix . '_general.png';
            } else {
                $file_path = STATIC_URL . '/images/default/' . $prefix . '_' . $res_name . '.png';
                return $file_path;
            }
        }

        // 如果是全路径 liw add 2014-11-11
        if (stripos($path, 'http') === 0) {
            return $path;
        }

        $path_info = pathinfo($path);
        $file_path = '';

        if (!empty($prefix)) {
            $file_path = $path_info['dirname'] . '/' . $prefix . '_' . $path_info['basename'];
        } else {
            $file_path = $path;
        }

        //如果传入的路径没有标明上传文件夹的话，则补全路径
        if (substr($file_path, 0, strlen(UPLOAD_FOLDER)) != UPLOAD_FOLDER) {
            $file_path = UPLOAD_FOLDER . '/' . ltrim($file_path, '/');
        }

        // if (!file_exists(ROOT_PATH.'/'.$file_path)) return '/static/images/default/general.gif';
        if (!file_exists(ROOT_PATH . '/' . $file_path)) {
            return '';
        }

        return STATIC_URL . '/' . $file_path;

    }
}

/**
 * 生成缩略图
 * @param $file_path 原图路径
 * @param $res_type 资源类型
 * @param $category_id 对应分类id
 * @return bool
 * @author gaojj@alltosun.com
 */
function make_thumb($file_path, $res_name, $category_id = 0, $prefix = '') {
    if (empty($res_name) || empty($file_path)) {
        return false;
    }

    // 从配置文件读取缩略图配置
    $thumb_set = get_res_thumb($res_name, $category_id);

    if (empty($thumb_set)) {
        return false;
    }

    $file_path = UPLOAD_PATH . $file_path;
    $path_info = pathinfo($file_path);

    // 缩略图模式，默认为切图
    $thumb_mode = 'cut';
    if (isset($thumb_set['mode'])) {
        $thumb_mode = $thumb_set['mode'];
        unset($thumb_set['mode']);
    }
    // 生成缩略图
    foreach ($thumb_set as $k => $v) {
        if (!empty($prefix) && $k != $prefix) {
            continue;
        }
        // 缩略图路径
        $thumb_path = $path_info['dirname'] . '/' . $k . '_' . $path_info['basename'];

        $new_width = $v[0];
        $new_height = $v[1];
        // 按照最大宽度/最大高度进行等比缩放
        if ($thumb_mode == 'max') {
            $gd = new Gd($file_path);
            // 如果原图的宽度小于指定缩放的宽度，则宽度不参与缩放
            if (empty($new_width) || $gd->width < $new_width) {
                $new_width = null;
            }
            // 如果原图的高度小于指定缩放的高度，则高度不参与缩放
            if (empty($new_height) || $gd->height < $new_height) {
                $new_height = null;
            }
            $retu1 = $gd->scale($new_width, $new_height);
            $retu2 = $gd->saveAs($thumb_path);
        } elseif ($thumb_mode == 'merge') {
            // 融图的方案
            $gd = Gd::create($new_width, $new_height, MERGE_BG);
            $gd2 = new Gd($file_path);
            $gd2->scale($new_width, $new_height);
            $gd->merge_auto($gd2);
            $gd->saveAs($thumb_path);
        } elseif ($thumb_mode == 'cut') {
            // 切图的方案，按照指定的宽高比进行缩放到指定的比例，再切去多余的图
            $gd = new Gd($file_path);
            $gd->scale_fill($new_width, $new_height);
            $gd->saveAs($thumb_path);
        }
    }

    return true;
}

/**
 * 从配置文件读取缩略图配置
 * @param mixed $res_type
 * @param $category_id 对应分类id
 * @return array
 * @author gaojj@alltosun.com
 */
function get_res_thumb($res_name, $category_id = 0) {
    $res_thumb = Config::get('res_thumb');

    $res_type = $res_name;
    if (is_numeric($res_type)) {
        $res_name = get_resource($res_type, 'name');
    }

    $thumb_set = isset($res_thumb[$res_name]) ? $res_thumb[$res_name] : array();

    // 支持资源的不同分类生成不同的缩略图
    if (isset($thumb_set['category'])) {
        // 如果传入category_id，则采用对应分类的缩略图设置
        if (!empty($category_id) && isset($thumb_set['category'][$category_id])) {
            return $thumb_set['category'][$category_id];
        }
        // 未定义该分类的缩略图设置，或者未传入category_id，则采用默认的缩略图设置
        return $thumb_set['category'][0];
    }

    return $thumb_set;
}

/**
 * 单条发送系统消息
 * 此方法的只为了简化系统消息的调用
 * @param $user_id Int //用户ID
 * @param $send_id Int //发件人ID
 * @param $type Int //类型区分
 * @param $param Int //附加参数,如果是回帖的话,则此处用作回帖人ID
 * @param $message String //信息内容
 * @return bool
 * @author gaojj@alltosun.com
 */
function send_sys_msg($user_id, $message = null, $send_id = 0, $type = 0, $param = 0) {
    //记录未读信息
    if (in_array($type, array(1, 2, 3, 4, 5))) {
        _model('message_unread')->create(array('user_id' => $user_id), "UPDATE friend=friend+1");
    } elseif (in_array($type, array(11, 12))) {
        _model('message_unread')->create(array('user_id' => $user_id), "UPDATE birthday=birthday+1");
    } else {
        _model('message_unread')->create(array('user_id' => $user_id), "UPDATE system_msg=system_msg+1");
    }
    $result = _model('system_msg')->create(array(
        'user_id' => $user_id,
        'send_id' => $send_id,
        'type' => $type,
        'param' => $param,
        'message' => $message
    ));
    return $result;
}

/**
 * 更新系统消息内容,封装的update方法
 * 此方法的只为了简化系统消息的调用
 * @param $option Array 条件,用法参见update的第一个参数
 * @param $data Array 更新内容,用法参见update的第二个参数
 * @author gaojj@alltosun.com
 */
function update_sys_msg($option, $data) {
    $result = _model('system_msg')->update($option, $data);
    return $result;
}

/**
 * 检查用户是否有访问该隐私的权限
 * @param $privacy  隐私设置（0-仅有自己；1-公开；2-仅有好友）
 * @param $user_id  访问者id
 * @param $owner_id 所有者id
 * @return bool
 * @author gaojj@alltosun.com
 */
function check_privacy($privacy, $user_id, $owner_id) {
    // 管理员 ok
    if (user_helper::is_admin()) {
        return true;
    }

    // 所有人可见
    if ($privacy == 1) {
        return true;
    }

    // 自己访问自己 ok
    if ($user_id == $owner_id) {
        return true;
    }

    // 当privacy =0 || 2时，都需要登录
    if (!$user_id) {
        return false;
    }

    // 仅好友
    if ($privacy == 2) {
        if (friend_helper::is_friend($user_id, $owner_id)) {
            return true;
        }

        if (user_helper::is_staff($owner_id) && user_helper::is_customer($user_id)) {
            return true;
        }

        if (user_helper::is_customer($owner_id) && user_helper::is_staff($user_id)) {
            return true;
        }
    }
    // 客户的仅自己可见对员工无效
    /*if ($privacy == 0) {
        if (user_helper::is_staff($user_id) && !user_helper::is_staff($owner_id)) return true;
    }*/

    return false;
}

/**
 * 获取文件的附件类型（用于`attachment`.`type`）
 * @param $file_path 文件路径
 * @return int 附件类型（1-图片；2-视频）
 * @author gaojj@alltosun.com
 */
function get_attachment_type($file_path) {
    $path_info = pathinfo($file_path);
    $attachment_type = 0;
    if (in_array(strtolower($path_info['extension']), Config::get('allow_image_type'))) {
        $attachment_type = 1;
    }
    if (in_array(strtolower($path_info['extension']), Config::get('allow_flash_type'))) {
        $attachment_type = 2;
    }

    //var_dump($path_info, $attachment_type);
    return $attachment_type;
}

/**
 * 处理具体资源自定义属性显示时的数据转换
 * @param int $attribute_id 属性id
 * @param mixed $attribute_value 具体资源自定义的属性值
 * @return string
 * @author gaojj@alltosun.com
 */
function attribute_value_display($attribute_id, $attribute_value) {
    $attribute_id = intval($attribute_id);

    if (empty($attribute_id) || empty($attribute_value)) {
        return '';
    }

    $attribute_info = _uri('attribute', $attribute_id);

    if (empty($attribute_info)) {
        return '';
    }

    if (in_array($attribute_info['type'], array('select', 'checkbox', 'radio'))) {
        return implode("&nbsp;", $attribute_value);
    }

    if ($attribute_info['type'] == 'file') {
        $file_ext = pathinfo($attribute_value, PATHINFO_EXTENSION);
        if (in_array($file_ext, Config::get('image_ext'))) {
            return '<img src="' . _image($attribute_value) . '" />';
        }
        return '<a href="' . _image($attribute_value) . '" target="_blank">点击查看</a>';
    }

    return $attribute_value;
}

/**
 * 获取用户的未读信息数
 * @param $user_id
 * @return int
 * @author gaojj@alltosun.com
 */
function unread_message($user_id) {
    if (empty($user_id)) {
        return 0;
    }
    return _model('message_member')->getTotal(array('to_user_id' => $user_id, 'is_read' => 0));
}

/**
 * 对ip进行处理
 * @param $ip
 * @return string
 * @author gaojj@alltosun.com
 * @FIXME
 */
function ip_treat($ip) {
    if (empty($ip)) {
        return '127.0.0.1';
    }
    list($a, $b, $c, $d) = explode('.', $ip);
    return $a . '.' . $b . '.' . $c . '.' . '*';
}

/**
 * @TODO
 * @param $sUBB
 */
function ubb2html($sUBB) {
    $sHtml = $sUBB;

    global $emotPath, $cnum, $arrcode, $bUbb2htmlFunctionInit;
    $cnum = 0;
    $arrcode = array();
    $emotPath = '../xheditor_emot/';//�����·��

    if (!$bUbb2htmlFunctionInit) {
        function saveCodeArea($match) {
            global $cnum, $arrcode;
            $cnum++;
            $arrcode[$cnum] = $match[0];
            return "[\tubbcodeplace_" . $cnum . "\t]";
        }
    }
    $sHtml = preg_replace_callback('/\[code\s*(?:=\s*((?:(?!")[\s\S])+?)(?:"[\s\S]*?)?)?\]([\s\S]*?)\[\/code\]/i', 'saveCodeArea', $sHtml);

    $sHtml = preg_replace("/&/", '&amp;', $sHtml);
    $sHtml = preg_replace("/</", '&lt;', $sHtml);
    $sHtml = preg_replace("/>/", '&gt;', $sHtml);
    $sHtml = preg_replace("/\r?\n/", '<br />', $sHtml);

    $sHtml = preg_replace("/\[(\/?)(b|u|i|s|sup|sub)\]/i", '<$1$2>', $sHtml);
    $sHtml = preg_replace('/\[color\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '<span style="color:$1;">', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getSizeName($match) {
            $arrSize = array('10px', '13px', '16px', '18px', '24px', '32px', '48px');
            if (preg_match("/^\d+$/", $match[1])) {
                $match[1] = $arrSize[$match[1] - 1];
            }
            return '<span style="font-size:' . $match[1] . ';">';
        }
    }
    $sHtml = preg_replace_callback('/\[size\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', 'getSizeName', $sHtml);
    $sHtml = preg_replace('/\[font\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '<span style="font-family:$1;">', $sHtml);
    $sHtml = preg_replace('/\[back\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]/i', '<span style="background-color:$1;">', $sHtml);
    $sHtml = preg_replace("/\[\/(color|size|font|back)\]/i", '</span>', $sHtml);

    for ($i = 0; $i < 3; $i++) {
        $sHtml = preg_replace('/\[align\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\](((?!\[align(?:\s+[^\]]+)?\])[\s\S])*?)\[\/align\]/', '<p align="$1">$2</p>', $sHtml);
    }
    $sHtml = preg_replace('/\[img\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/img\]/i', '<img src="$1" alt="" />', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getImg($match) {
            $alt = $match[1];
            $p1 = $match[2];
            $p2 = $match[3];
            $p3 = $match[4];
            $src = $match[5];
            $a = $p3 ? $p3 : (!is_numeric($p1) ? $p1 : '');
            return '<img src="' .
                   $src .
                   '" alt="' .
                   $alt .
                   '"' .
                   (is_numeric($p1) ? ' width="' . $p1 . '"' : '') .
                   (is_numeric($p2) ? ' height="' . $p2 . '"' : '') .
                   ($a ? ' align="' . $a . '"' : '') .
                   ' />';
        }
    }
    $sHtml = preg_replace_callback('/\[img\s*=([^,\]]*)(?:\s*,\s*(\d*%?)\s*,\s*(\d*%?)\s*)?(?:,?\s*(\w+))?\s*\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*)?\s*\[\/img\]/i', 'getImg', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getEmot($match) {
            global $emotPath;
            $arr = split(',', $match[1]);
            if (!isset($arr[1])) {
                $arr[1] = $arr[0];
                $arr[0] = 'default';
            }
            $path = $emotPath . $arr[0] . '/' . $arr[1] . '.gif';
            return '<img src="' . $path . '" alt="' . $arr[1] . '" />';
        }
    }
    $sHtml = preg_replace_callback('/\[emot\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\/\]/i', 'getEmot', $sHtml);
    $sHtml = preg_replace('/\[url\]\s*(((?!")[\s\S])*?)(?:"[\s\S]*?)?\s*\[\/url\]/i', '<a href="$1">$1</a>', $sHtml);
    $sHtml = preg_replace('/\[url\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]*?)\s*\[\/url\]/i', '<a href="$1">$2</a>', $sHtml);
    $sHtml = preg_replace('/\[email\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/email\]/i', '<a href="mailto:$1">$1</a>', $sHtml);
    $sHtml = preg_replace('/\[email\s*=\s*([^\]"]+?)(?:"[^\]]*?)?\s*\]\s*([\s\S]+?)\s*\[\/email\]/i', '<a href="mailto:$1">$2</a>', $sHtml);
    $sHtml = preg_replace("/\[quote\]([\s\S]*?)\[\/quote\]/i", '<blockquote>$1</blockquote>', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getFlash($match) {
            $w = $match[1];
            $h = $match[2];
            $url = $match[3];
            if (!$w) {
                $w = 480;
            }
            if (!$h) {
                $h = 400;
            }
            return '<embed type="application/x-shockwave-flash" src="' .
                   $url .
                   '" wmode="opaque" quality="high" bgcolor="#ffffff" menu="false" play="true" loop="true" width="' .
                   $w .
                   '" height="' .
                   $h .
                   '" />';
        }
    }
    $sHtml = preg_replace_callback('/\[flash\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/flash\]/i', 'getFlash', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getMedia($match) {
            $w = $match[1];
            $h = $match[2];
            $play = $match[3];
            $url = $match[4];
            if (!$w) {
                $w = 480;
            }
            if (!$h) {
                $h = 400;
            }
            return '<embed type="application/x-mplayer2" src="' .
                   $url .
                   '" enablecontextmenu="false" autostart="' .
                   ($play == '1' ? 'true' : 'false') .
                   '" width="' .
                   $w .
                   '" height="' .
                   $h .
                   '" />';
        }
    }
    $sHtml = preg_replace_callback('/\[media\s*(?:=\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d+)\s*)?)?\]\s*(((?!")[\s\S])+?)(?:"[\s\S]*?)?\s*\[\/media\]/i', 'getMedia', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getTable($match) {
            return '<table' .
                   (isset($match[1]) ? ' width="' . $match[1] . '"' : '') .
                   (isset($match[2]) ? ' bgcolor="' . $match[2] . '"' : '') .
                   '>';
        }
    }
    $sHtml = preg_replace_callback('/\[table\s*(?:=(\d{1,4}%?)\s*(?:,\s*([^\]"]+)(?:"[^\]]*?)?)?)?\s*\]/i', 'getTable', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getTR($match) {
            return '<tr' . (isset($match[1]) ? ' bgcolor="' . $match[1] . '"' : '') . '>';
        }
    }
    $sHtml = preg_replace_callback('/\[tr\s*(?:=(\s*[^\]"]+))?(?:"[^\]]*?)?\s*\]/i', 'getTR', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getTD($match) {
            $col = isset($match[1]) ? $match[1] : 0;
            $row = isset($match[2]) ? $match[2] : 0;
            $w = isset($match[3]) ? $match[3] : null;
            return '<td' .
                   ($col > 1 ? ' colspan="' . $col . '"' : '') .
                   ($row > 1 ? ' rowspan="' . $row . '"' : '') .
                   ($w ? ' width="' . $w . '"' : '') .
                   '>';
        }
    }
    $sHtml = preg_replace_callback("/\[td\s*(?:=\s*(\d{1,2})\s*,\s*(\d{1,2})\s*(?:,\s*(\d{1,4}%?))?)?\s*\]/i", 'getTD', $sHtml);
    $sHtml = preg_replace("/\[\/(table|tr|td)\]/i", '</$1>', $sHtml);
    $sHtml = preg_replace("/\[\*\]((?:(?!\[\*\]|\[\/list\]|\[list\s*(?:=[^\]]+)?\])[\s\S])+)/i", '<li>$1</li>', $sHtml);
    if (!$bUbb2htmlFunctionInit) {
        function getUL($match) {
            $str = '<ul';
            if (isset($match[1])) {
                $str .= ' type="' . $match[1] . '"';
            }
            return $str . '>';
        }
    }
    $sHtml = preg_replace_callback('/\[list\s*(?:=\s*([^\]"]+))?(?:"[^\]]*?)?\s*\]/i', 'getUL', $sHtml);
    $sHtml = preg_replace("/\[\/list\]/i", '</ul>', $sHtml);
    $sHtml = preg_replace("/\[hr\/\]/i", '<hr />', $sHtml);

    for ($i = 1; $i <= $cnum; $i++) {
        $sHtml = str_replace("[\tubbcodeplace_" . $i . "\t]", $arrcode[$i], $sHtml);
    }

    if (!$bUbb2htmlFunctionInit) {
        function fixText($match) {
            $text = $match[2];
            $text = preg_replace("/\t/", '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;', $text);
            $text = preg_replace("/ /", '&nbsp;', $text);
            return $match[1] . $text;
        }
    }
    $sHtml = preg_replace_callback('/(^|<\/?\w+(?:\s+[^>]*?)?>)([^<$]+)/i', 'fixText', $sHtml);

    $bUbb2htmlFunctionInit = true;

    return $sHtml;
}

function upon_data($id, $aim = 'prev', $title = '') {
    // 2010.08.19 gaojj add support for media res_type
    $blog_info = _uri('blog', $id);
    $user_id = $blog_info['user_id'];

    if ($aim == 'prev') {
        // @FIXME date->id, getFields->read
        $date = _model('blog')->getFields('id', array(
            'user_id' => $user_id,
            'res_type' => $blog_info['res_type'],
            'status' => 1,
            'id<' => $id
        ), 'ORDER BY `id` DESC LIMIT 1');
    } else {
        $date = _model('blog')->getFields('id', array(
            'user_id' => $user_id,
            'res_type' => $blog_info['res_type'],
            'status' => 1,
            'id>' => $id
        ), 'ORDER BY `id` ASC LIMIT 1');
    }
    $blog_id = $date[0] ? $date[0] : 0;
    if ($title) {
        return _uri('blog', $blog_id, 'title');
    } else {
        return $blog_id;
    }
}


/**
 * 为空值变量设置默认值
 * @param mixed $variable
 * @param mixed $default
 * @param int $backend 在后台显示（默认为在前台显示，在后台显示时永远返回''）
 * @return int
 * @author liww@alltosun.com
 */
function default_int($variable, $default = '', $backend = 0) {
    $variable = (int)$variable;

    if (!empty($variable)) {
        return $variable;
    }

    if ($backend) {
        return 0;
    }

    return $default;
}

/**
 * 清除字符串中的ubb标签
 * @param string $str
 * @return string
 * @author gaojj@alltosun.com
 */
function clean_ubb($str) {
    return preg_replace("/^\[\S+\]$/U", "", $str);
}

/**
 * 图片缩放
 * @param $path 图片路径
 * @param $max_width 缩放最大宽度
 * @param $max_height 缩放最大高度
 * @param $key
 * @return array 与getimagesize()返回的数据结构相同
 */
function image_scale($path, $max_width = 0, $max_height = 0, $key = null) {
    $path = ROOT_PATH . '/' . _image($path);
    $size = getimagesize($path);
    if (!$size) {
        return false;
    }
    $width = $size[0];
    $height = $size[1];

    if ($max_width && $width > $max_width) {
        $height = $max_width / $width * $height;
        $width = $max_width;
    }

    if ($max_height && $height > $max_height) {
        $width = $max_height / $height * $width;
        $height = $max_height;
    }

    $array = array($width, $height, $size[2], " width=\"$width\" height=\"$height\"");

    if (isset($key)) {
        return $array[$key];
    }
    return $array;
}

/**
 * 判断用户是否是某资源作者
 * @param int $res_id
 * @param int $res_type
 * @param int $user_id
 * @author liww@alltosun.com
 */
function is_author($res_type, $res_id, $user_id) {
    if (!$user_id || !$res_type || !$res_id) {
        return false;
    }

    if (is_numeric($res_type)) {
        $res_name = get_resource($res_type, 'name');
    } else {
        $res_name = $res_type;
    }

    // 获取资源的作者
    $author_id = _uri($res_name, $res_id, 'user_id');

    return $user_id == $author_id;
}

/**
 * 获取图片的信息
 * @param string $name 图片名字(带路径)
 * @author qianym@alltosun.com
 */
function get_image_info($filename) {
    // 或该图不存在，则直接返加为空
    if (!file_exists($filename)) {
        return array();
    }

    $data = getimagesize($filename);
    $imgInfo["width"] = $data[0];
    $imgInfo["height"] = $data[1];
    $imgInfo["type"] = $data[2];

    return $imgInfo;
}


/**
 * 格式化时间
 * @param null $time
 * @param string $format
 * @return bool|string
 */
function datetime($timestamp = null, $format = "Y-m-d H:i:s") {
    if ($timestamp > 0) {
        return date($format, $timestamp);
    } else {
        return date($format);
    }
}

/**
 * 字符串|数组|对象金钱格式化
 * @param decimal|array|object $data
 * @param string $field
 * @return decimal|array|object
 */
function format_money($data, $field = '') {
    if (!$data) {
        return $data;
    }

    if (is_array($data)) {
        foreach ($data as $key => $value) {
            $data[$key][$field] = num_keep_two_round($value[$field]);
        }
    } elseif (is_object($data)) {
        foreach ($data as $key => $value) {
            $data->$key->$field = num_keep_two_round($value->$field);
        }
    } else {
        $data = num_keep_two_round($data);
    }

    return $data;
}

/**
 * 获取事务对象或非事务对象
 * @param string $table_name
 * @param int $is_ts 是否支持事务(0:不支持,1:支持)
 * @return object
 */
function _model_ts($table_name, $is_ts = 0) {
    if ($is_ts) {
        return ts_helper::_model($table_name);
    } else {
        return _model($table_name);
    }
}

/**
 * 执行SQL
 * * 不建立缓存
 *
 * @param $table
 * @param string $action
 * @param string $sql
 * @return array
 * @throws AnException
 */
function run_sql($table, $action = 'getAll', $sql = '') {

    $ret = array();

    if (empty($sql)) {
        return $ret;
    }

    return _model('operator')->run($table, $action, $sql);
}


